package tec.stan.ling.topo.demo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.xmappr.Xmappr;

import tec.stan.ling.core.notifier.Adapter;
import tec.stan.ling.core.notifier.Notification;
import tec.stan.ling.core.top.model.Device;
import tec.stan.ling.core.top.model.Link;
import tec.stan.ling.core.top.model.NEState;
import tec.stan.ling.core.top.model.NEType;
import tec.stan.ling.core.top.model.Subnet;
import tec.stan.ling.topo.model.DeviceImpl;
import tec.stan.ling.topo.model.LinkImpl;
import tec.stan.ling.topo.model.SubnetImpl;

public class DemoUtil {

	private static final org.apache.log4j.Logger log = org.apache.log4j.Logger
			.getLogger(DemoUtil.class);

	public static Subnet loadNE(IFile file) {
		if (file.exists()) {
			Xmappr xmappr = new Xmappr(SubnetImpl.class);
			try {
				Object object = xmappr.fromXML(new InputStreamReader(file
						.getContents()));
				return (Subnet) object;
			} catch (CoreException e) {
				log.debug(e.getMessage(), e);
			}
		}
		return null;
	}

	public static void saveNE(IFile file, Subnet root) {
		Xmappr xmappr = new Xmappr(SubnetImpl.class);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		xmappr.toXML(root, new OutputStreamWriter(out));

		ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

		try {
			if (!file.exists()) {
				file.create(in, true, null);
			} else {
				file.setContents(in, true, false, null);
			}
		} catch (Exception e) {
			log.debug(e.getMessage(), e);
		}
	}

	public static Subnet createDemo() {
		Subnet root = new SubnetImpl(0,null);
		root.setName("Root");
		
//		Subnet subnet = new SubnetImpl(1, root);
//		subnet.setName("Subnet");
//		subnet.setX(10);
//		subnet.setY(10);
//		root.getChildren().add(subnet);
		
		Device ne1 = new DeviceImpl(2,root);
		ne1.setName("ne1");
		ne1.setX(0);
		ne1.setY(0);		
		root.getChildren().add(ne1);

		Device ne2 = new DeviceImpl(3,root);
		ne2.setName("ne2");
		ne2.setX(100);
		ne2.setY(300);
		root.getChildren().add(ne2);

		Link linker1 = new LinkImpl(4,ne1,ne2);
		linker1.setName("Linker1");
		ne1.getOutputLinks().add(linker1);
		ne2.getInputLinks().add(linker1);

		return root;
	}
}
